package com.vikutorika.servlet;

import cn.hutool.json.JSONUtil;
import com.vikutorika.dao.GroupTextMessageDAO;
import com.vikutorika.dao.GroupUserDAO;
import com.vikutorika.dao.PersonalTextMessageDAO;
import com.vikutorika.dao.imp.GroupTextMessageDAOImp;
import com.vikutorika.dao.imp.GroupUserDAOImp;
import com.vikutorika.entity.GroupTextMessage;
import com.vikutorika.entity.GroupUser;
import com.vikutorika.entity.PersonalTextMessage;
import com.vikutorika.service.MessageService;
import com.vikutorika.util.ParamUtil;
import com.vikutorika.dao.imp.PersonalTextMessageDAOImp;
import com.vikutorika.vo.PullMessageRequestVo;
import com.vikutorika.vo.ResultVo;
import com.vikutorika.vo.SendMessageVo;
import com.vikutorika.vo.UnreadMessageEventVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@WebServlet("/chat")
public class PrivateChatServlet extends BaseServlet {
    /**
     * 拉取对方发送未读消息
     *
     * @param req
     * @param resp
     */

    public void setUid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer uid = Integer.valueOf(req.getParameter("uid"));
        req.getSession().setAttribute("uid", uid);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(JSONUtil.toJsonStr(ResultVo.success()));
        msgs.put(uid, new ConcurrentHashMap<>());
    }

    public void pullUnread(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PullMessageRequestVo vo = ParamUtil.paramToBean(req, PullMessageRequestVo.class);
        ResultVo resultVo = null;
        Map<String, UnreadMessageEventVo> mMap = msgs.get(vo.getUid());
        if (vo.getType().equals("私聊")) {
            resultVo = MessageService.PullPersonalUnread(vo, vo.getUid());
            if(mMap!=null)
            {
                mMap.remove("私聊"+vo.getId());
            }
        } else {
            resultVo = MessageService.PullGroupUnread(vo, vo.getUid());
            if(mMap!=null)
            {
                mMap.remove("群聊"+vo.getId());
            }
        }
        if (resultVo.getCode().equals("200")) {
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(JSONUtil.toJsonStr(resultVo));
        }
    }

    //在登陆成功时创建(uid,未读消息对象map)，并加入
    public static Map<Integer, Map<String, UnreadMessageEventVo>> msgs = new ConcurrentHashMap<>();
    public void pullOfflineUnread(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
        Integer uid = Integer.valueOf(req.getParameter("uid"));
        ResultVo resultVo = MessageService.getAllUnreadDigest(uid);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(JSONUtil.toJsonStr(resultVo));
    }

    public void waitMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer uid = Integer.valueOf(req.getParameter("uid"));
        Map<String, UnreadMessageEventVo> mMap = msgs.get(uid);
        resp.setContentType("application/json;charset=utf8");
        if (mMap.isEmpty()) {//无任何未读消息
            synchronized (mMap) {
                if (mMap.isEmpty()) {
                    try {
                        mMap.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        String jsonStr = JSONUtil.toJsonStr(mMap.values());
        resp.getWriter().write(jsonStr);
    }

    /**
     * 拉取历史消息
     *
     * @param req
     * @param resp
     */
    public void pullHistory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PullMessageRequestVo vo = ParamUtil.paramToBean(req, PullMessageRequestVo.class);
        ResultVo resultVo = null;

        Map<String, UnreadMessageEventVo> mMap = msgs.get(vo.getUid());
        if (vo.getType().equals("私聊")) {
            resultVo = MessageService.PullPersonalHistory(vo);
            if(mMap!=null)
            {
                mMap.remove("私聊"+vo.getId());
            }
        } else {
            resultVo = MessageService.PullGroupHistory(vo);
            if(mMap!=null)
            {
                mMap.remove("群聊"+vo.getId());
            }
        }
        if (resultVo.getCode().equals("200")) {
            resp.setContentType("application/json;charset=utf8");
            resp.getWriter().write(JSONUtil.toJsonStr(resultVo));
        }
    }
    /**
     * 给对方发送未读信息
     *
     * @param req
     * @param resp
     */
    public void sendMessage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SendMessageVo messageVo = ParamUtil.paramToBean(req, SendMessageVo.class);
        ResultVo resultVo = null;
        if (messageVo.getType().equals("私聊")) {
            resultVo = MessageService.newPersonalMessage(messageVo);
            Integer receiver_uid = messageVo.getId();
            Map<String, UnreadMessageEventVo> mMap = msgs.get(receiver_uid);
            if (mMap != null) {        //对方在线
                UnreadMessageEventVo umeVo = mMap.get("私聊"+messageVo.getUid());
                if (umeVo != null) {        //有发送事件对象
                    umeVo.setCount(umeVo.getCount() + 1);
                    umeVo.setRecent_content(messageVo.getContent());
                } else {
                    umeVo = new UnreadMessageEventVo("私聊", messageVo.getUid(), 1, messageVo.getContent());
                    mMap.put("私聊"+messageVo.getUid(), umeVo);
                }
                synchronized (mMap) {
                    mMap.notify();
                }
            }
        } else {
            resultVo = MessageService.newGroupMessage(messageVo);
            Integer gid = messageVo.getId();
            List<GroupUser> users = new GroupUserDAOImp().getByGID(gid);
            for (GroupUser user : users) {
                if (user.getUid() .equals(messageVo.getUid())) {
                    continue;
                }
                Map<String, UnreadMessageEventVo> mMap = msgs.get(user.getUid());
                if (mMap != null) {        //对方在线
                    UnreadMessageEventVo umeVo = mMap.get("群聊"+gid);
                    if (umeVo != null) {        //有发送事件对象
                        umeVo.setCount(umeVo.getCount() + 1);
                        umeVo.setRecent_content(messageVo.getContent());
                    } else {
                        umeVo = new UnreadMessageEventVo("群聊", messageVo.getId(), 1, messageVo.getContent());
                        mMap.put("群聊"+gid, umeVo);
                    }
                    synchronized (mMap) {
                        mMap.notify();
                    }
                }
            }
        }
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(JSONUtil.toJsonStr(resultVo));
    }
}
